Categories
MongoDB

Using MongoDB with Mongoose — Discriminators and Arrays

Spread the love

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Embedded Discriminators in Arrays

We can add embedded discriminators into arrays.

For example, we can write:

async function run() {
  const { createConnection, Types, Schema } = require('mongoose');
  const db = createConnection('mongodb://localhost:27017/test');
  const eventSchema = new Schema({ message: String },
    { discriminatorKey: 'kind', _id: false });

  const batchSchema = new Schema({ events: [eventSchema] });
  const docArray = batchSchema.path('events');
  const clickedSchema = new Schema({
    element: {
      type: String,
      required: true
    }
  }, { _id: false });
  const Clicked = docArray.discriminator('Clicked', clickedSchema);
  const Purchased = docArray.discriminator('Purchased', new Schema({
    product: {
      type: String,
      required: true
    }
  }, { _id: false }));

  const Batch = db.model('EventBatch', batchSchema);
  const batch = {
    events: [
      { kind: 'Clicked', element: '#foo', message: 'foo' },
      { kind: 'Purchased', product: 'toy', message: 'world' }
    ]
  };
  const doc = await Batch.create(batch);
  console.log(doc.events);
}
run();

We add the events array into the eventSchema .

Then we create the docArray by calling the batchSchema.path method so that we can create the discriminator with the docArray method.

Then we create the discriminators by calling docArray.discriminator method with the name of the model and the schema.

Next, we create the Batch model from the batchSchema so that we can populate the model.

We call Batch.create with the batch object that has an events array property to add the items.

The kind property has the type of object we want to add.

Then doc.events has the event entries, which are:

[
  { kind: 'Clicked', element: '#foo', message: 'foo' },
  { kind: 'Purchased', product: 'toy', message: 'world' }
]

Recursive Embedded Discriminators in Arrays

We can also add embedded discriminators recursively in arrays.

For example, we can write:

async function run() {
  const { createConnection, Types, Schema } = require('mongoose');
  const db = createConnection('mongodb://localhost:27017/test');
  const singleEventSchema = new Schema({ message: String },
    { discriminatorKey: 'kind', _id: false });

  const eventListSchema = new Schema({ events: [singleEventSchema] });

  const subEventSchema = new Schema({
    subEvents: [singleEventSchema]
  }, { _id: false });

  const SubEvent = subEventSchema.path('subEvents').
    discriminator('SubEvent', subEventSchema);
  eventListSchema.path('events').discriminator('SubEvent', subEventSchema);

  const Eventlist = db.model('EventList', eventListSchema);
  const list = {
    events: [
      { kind: 'SubEvent', subEvents: [{ kind: 'SubEvent', subEvents: [], message: 'test1' }], message: 'hello' },
      { kind: 'SubEvent', subEvents: [{ kind: 'SubEvent', subEvents: [{ kind: 'SubEvent', subEvents: [], message: 'test3' }], message: 'test2' }], message: 'world' }
    ]
  };

  const doc = await Eventlist.create(list)
  console.log(doc.events);
  console.log(doc.events[1].subEvents);
  console.log(doc.events[1].subEvents[0].subEvents);
}
run();

We create the singleEventSchema .

Then we use as the schema for the objects in the events array property.

Next, we create the subEventSchema the same way.

Then we create the SubEvent model calling the path and the discriminator methods.

This will create the schema for the subEvents property.

Then we link that to the events property with the:

eventListSchema.path('events').discriminator('SubEvent', subEventSchema);

call.

Now we have can subEvents properties in events array entrys that are recursive.

Next, we create the list object with the events array that has the subEvents property added recursively.

Then we call Eventlist.create to create the items.

The last 2 console logs should get the subevents from the 2nd event entry.

Conclusion

We can add discriminators to arrays and also add them recursively.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *